<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{
            userInfo.role === "Admin" ? "投诉建议管理" : "我的投诉"
          }}</span>
          <el-button
            v-if="userInfo.role !== 'Admin'"
            type="primary"
            @click="handleAdd"
            >提交投诉</el-button
          >
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="处理状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择处理状态"
            clearable
            style="width: 100px"
          >
            <el-option label="待处理" value="Pending" />
            <el-option label="已处理" value="Processed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="complaintList" style="width: 100%">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="description" label="投诉内容" />
        <el-table-column prop="user.name" label="投诉人" width="120" />
        <el-table-column prop="response" label="回复内容" width="120" />
        <el-table-column prop="createdAt" label="提交时间" width="180">
          <template #default="scope">
            {{ dayjs(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status === "Pending" ? "待处理" : "已处理" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              v-if="userInfo.role === 'Admin' && scope.row.status === 'Pending'"
              type="primary"
              link
              @click="handleReply(scope.row)"
              >回复</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager,next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-if="userInfo.role === 'Admin'"
      title="回复投诉"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="form.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交投诉对话框 -->
    <el-dialog
      v-if="userInfo.role !== 'Admin'"
      title="提交投诉"
      v-model="addDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入投诉标题" />
        </el-form-item>
        <el-form-item label="内容" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入投诉内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddSubmit">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import {
  getComplaintList,
  replyComplaint,
  createComplaint,
} from "@/api/complaint";

const router = useRouter();
const loading = ref(false);
const dialogVisible = ref(false);
const addDialogVisible = ref(false);
const total = ref(0);
const complaintList = ref([]);
const formRef = ref(null);
const addFormRef = ref(null);

// 用户信息
const userInfo = ref({
  username: "",
  role: "",
});

// 获取用户信息
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    userInfo.value = JSON.parse(userInfoStr);
  }
});

// 查询参数
const queryParams = reactive({
  pageNumber: 1,
  pageSize: 10,
  status: "",
});

// 表单数据
const form = reactive({
  id: undefined,
  reply: "",
});

// 添加表单数据
const addForm = reactive({
  title: "",
  description: "",
});

// 表单验证规则
const rules = {
  reply: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
};

// 添加表单验证规则
const addRules = {
  title: [{ required: true, message: "请输入投诉标题", trigger: "blur" }],
  description: [{ required: true, message: "请输入投诉内容", trigger: "blur" }],
};

// 获取投诉列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getComplaintList(queryParams);
    complaintList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取投诉列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNumber = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.status = "";
  handleQuery();
};

// 查看按钮操作
const handleView = (row) => {
  router.push(`/complaint/detail/${row.id}`);
};

// 回复按钮操作
const handleReply = (row) => {
  form.id = row.id;
  form.reply = "";
  dialogVisible.value = true;
};

// 添加按钮操作
const handleAdd = () => {
  addForm.title = "";
  addForm.description = "";
  addDialogVisible.value = true;
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await replyComplaint(form.id, { reply: form.reply });
        ElMessage.success("回复成功");
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("回复失败:", error);
      }
    }
  });
};

// 添加表单提交
const handleAddSubmit = async () => {
  if (!addFormRef.value) return;
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await createComplaint(addForm);
        ElMessage.success("提交成功");
        addDialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("提交失败:", error);
      }
    }
  });
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNumber = val;
  getList();
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    Pending: "info",
    Processed: "success",
  };
  return statusMap[status] || "info";
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
